package com.hxzy.springbootrocketproducer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.springbootrocketproducer.dto.UserChargeDTO;
import com.hxzy.springbootrocketproducer.entity.MqTransactionLog;
import com.hxzy.springbootrocketproducer.entity.User;
import com.hxzy.springbootrocketproducer.mapper.MqTransactionLogMpper;
import com.hxzy.springbootrocketproducer.mapper.UserMapper;
import com.hxzy.springbootrocketproducer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MqTransactionLogMpper mqTransactionLogMpper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addBalance(UserChargeDTO userCharge, String transactionId) {
        //一、更新用户积分
        //1、先根据ID查询用户原始数据
        User dbUser=this.userMapper.selectById(userCharge.getId());
        //2、把原来的金额取出  + 本次冲值的金额
        int money= userCharge.getBalance() + dbUser.getBalance();
        User newUser=new User();
        newUser.setId(userCharge.getId());
        newUser.setBalance(money);
        //3、更新
        this.userMapper.updateById(newUser);

        //二、添加事务日志
        MqTransactionLog  log=new MqTransactionLog();
        log.setTransactionId(transactionId);
        log.setLog(JSONObject.toJSONString(userCharge));
        //写入
        this.mqTransactionLogMpper.insert(log);

        return 1;
    }
}
